//
//  QCAbountViewController+BIN.swift
//  爱汽车
//
//  Created by xinglian on 2024/4/9.
//

import UIKit
import TCCKit

//MARK: - BIN文件OTA - START
extension QCAboutViewController{
    ///BIN文件开始OTA
    func BIN_OTA(){
        BLEData.clearBIN("00FFFFFF"+"00FFFFFF"+"\(current_OTA_Model.binCode)"+"\(current_OTA_Model.code)"+"\(current_OTA_Model.binVersion)").write
    }
    
    func addNotifyForBin(){
        NotifyTool.add(self, #selector(methodClearBin), BLEData.clearBIN("").ack)
        NotifyTool.add(self, #selector(actionForBLE3106Response), BLEData.sendImgData(Data()).ack)
    }
    
    @objc private func methodClearBin(_ notify:Notification){
        guard let userinfo = notify.userInfo as? [String:String] else{return}
        guard let status = userinfo["data"] else{return}
        switch status {
        case "02":
            handleData()
        default:
            break
        }
    }
    
    //分包返回
    @objc private func actionForBLE3106Response(notify:Notification){
        guard let userinfo = notify.userInfo else{return}
        guard let value = userinfo["value"] as? String else{return}
        switch value{
        case "01","03","04":
            let per = String(format:"%d%%", Int(CGFloat(bin_index)/CGFloat(bin_array.count)*100))
            sendData()
            // if showCChud == false{return}
            CCHud.start(LS("发送数据中...")+per)
            btnState(text: LS("更新")+"\(per)", index: btn_select_index)
            print("某个数据异常，忽略")
        case "02":
            bin_index = bin_array.count
            let per = String(format:"%d%%", Int(CGFloat(bin_index)/CGFloat(bin_array.count)*100))
            
            // if showCChud == false{return}
            CCHud.start(LS("发送数据中...")+per, stopTime: 2)
            btnState(text: LS("更新")+"\(per)", index: btn_select_index)
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {[weak self] in
                guard let self = self else{return}
                self.btnState(text: LS("已是最新"), index: self.btn_select_index)
            })
            print("更新成功")
        case "05":
            bin_index += 1
            let per = String(format:"%d%%", Int(CGFloat(bin_index)/CGFloat(bin_array.count)*100))
            sendData()
            //if showCChud == false{return}
            CCHud.start(LS("发送数据中...")+per)
            btnState(text: LS("更新")+"\(per)", index: btn_select_index)
            MyPrint("=====写入\(bin_index)/\(bin_array.count)数据")
        case "06":
            btnState(text: "更新失败", index: btn_select_index)
            CCHud.start(LS("异常退出，包含超时"), stopTime: 2){
                self.navigationController?.popViewController(animated: true)
            }
            print("异常退出，包含超时")
        default:
            break
        }
    }
    
    /// bin文件拆分
    private func handleData()
    {
        ///这里是工程测试bin文件
        /*let path = Bundle.main.url(forResource: "test", withExtension: "bin")
         let data = NSData(data: try! Data(contentsOf: path!))*/
        guard let data = current_OTA_Model.data as? NSData else{return}
        bin_index = 0
        bin_array.removeAll()
        
        let count =  data.length/4096 + (data.length%4096 > 0 ? 1 : 0)
        var length = 1024 * 4
        for i in 0 ..< count
        {
            let subData = NSMutableData()
            var tempData = NSData()
            var subArray = Array<NSMutableData>()
            length = (i == count - 1) ? data.length%4096 : length
            if i == 0
            {
                let totalLength = "\(data.length + 17)".toHex().fix(8, "0")
                ///command+key+索引 01+索引后面数据的字节长度+起始位置+结束位置+CRC+固定结尾
                ///自定义表盘和市场表盘开始和结束都是 0x00FFFFFF   16777215
                let firstData = "0805"+"01"+"0009"+"00FFFFFF"+"00FFFFFF"+"02"+"02FFFF"
                let header = String(format:"880000%@00%@", totalLength, firstData)
                subData.append(header.hexadecimal()!)
            }
            tempData = data.subdata(with: NSRange(location:i*4096, length:length)) as NSData
            subData.append(tempData as Data)
            
            //拆181小包
            let subDataCount = subData.count/181 + (subData.count%181 > 0 ? 1 : 0)
            var subDataLength = 181
            
            for j in 0 ..< subDataCount
            {
                subDataLength = (j == subDataCount - 1) ? subData.count%181 : subDataLength
                let data181 = subData.subdata(with:NSRange(location:j*181, length:subDataLength))
                subArray.append(crc8Data(data181 as NSData) as! NSMutableData)
                
            }
            bin_array.append(subArray)
        }
        sendData()
    }
    
    ///手动插入CRC
    private func crc8Data(_ data : NSData)->NSData
    {
        let mutdata = NSMutableData.init(data:data as Data)
        var byes = [UInt8](data)
        for i in 1..<data.length
        {
            byes[0] = byes[0] ^ byes[i]
        }
        byes[0] = byes[0] & 0xff
        let resultData = NSData.init(bytes: byes, length:1)
        mutdata.append(resultData as Data)
        return mutdata
    }
    
    ///发送小包
    private func sendData(){
        if bin_array.count <= 0 || bin_index >= bin_array.count {return}
        let subArray = bin_array[bin_index] as! Array<NSMutableData>
        for data in subArray
        {
            BLEData.sendImgData(data as Data).write
        }
    }
}
//MARK: - BIN文件OTA - END
